<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
import { 
    EllipsisHorizontalIcon,
    MagnifyingGlassIcon,
    ChevronUpIcon,
    ChevronDownIcon,
    UserIcon,
    PlusIcon,
    PencilIcon,
    TrashIcon,
    EyeIcon,
    DocumentTextIcon,
    ChatBubbleLeftIcon
} from '@heroicons/vue/24/outline'
import debounce from 'lodash/debounce'
import Pagination from '@/Components/UI/Pagination.vue'
import ConfirmDialog from '@/Components/UI/ConfirmDialog.vue'
import { useToast } from '@/Composables/useToast'

const props = defineProps({
    users: {
        type: Object,
        required: true
    },
    filters: {
        type: Object,
        default: () => ({})
    },
    stats: {
        type: Object,
        default: () => ({})
    }
})

const toast = useToast()
const search = ref(props.filters.search || '')
const sort = ref(props.filters.sort || '')

// 删除确认
const showDeleteConfirm = ref(false)
const userToDelete = ref(null)

// 处理搜索
const handleSearch = debounce(() => {
    router.get(route('admin.users.index'), {
        search: search.value,
        sort: sort.value
    }, {
        preserveState: true,
        preserveScroll: true
    })
}, 300)

// 处理排序
const handleSort = (field) => {
    const currentSort = sort.value || ''
    if (currentSort === `${field},asc`) {
        sort.value = `${field},desc`
    } else if (currentSort === `${field},desc`) {
        sort.value = ''
    } else {
        sort.value = `${field},asc`
    }
    handleSearch()
}

// 获取排序状态
const getSortDirection = (field) => {
    const currentSort = sort.value || ''
    if (currentSort === `${field},asc`) return 'asc'
    if (currentSort === `${field},desc`) return 'desc'
    return null
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未验证'
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    })
}

// 删除用户
const confirmDelete = (user) => {
    userToDelete.value = user
    showDeleteConfirm.value = true
}

const cancelDelete = () => {
    showDeleteConfirm.value = false
    userToDelete.value = null
}

const deleteUser = () => {
    router.delete(route('admin.users.destroy', userToDelete.value.id), {
        onSuccess: () => {
            toast.success('用户删除成功')
            showDeleteConfirm.value = false
            userToDelete.value = null
        },
        onError: (errors) => {
            console.error('删除失败：', errors)
            toast.error('删除失败，请重试')
        }
    })
}
</script>

<template>
    <AdminLayout>
        <Head title="用户管理" />

        <div class="space-y-6">
            <!-- 页面标题和操作 -->
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">用户管理</h1>
                    <p class="mt-2 text-sm text-gray-600">
                        共 {{ users.meta?.total || 0 }} 位用户
                    </p>
                </div>
                <Link
                    :href="route('admin.users.create')"
                    class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 transition-colors"
                >
                    <PlusIcon class="h-5 w-5" />
                    新建用户
                </Link>
            </div>

            <!-- 搜索栏 -->
            <div class="flex flex-col sm:flex-row gap-4">
                <div class="flex-1">
                    <div class="relative">
                        <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                            <MagnifyingGlassIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                        </div>
                        <input
                            type="search"
                            v-model="search"
                            placeholder="搜索用户名或邮箱..."
                            class="block w-full rounded-md border border-gray-300 bg-white py-2 pl-10 pr-3 text-sm placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                            @input="handleSearch"
                        >
                    </div>
                </div>
            </div>

            <!-- 用户列表表格 -->
            <div class="overflow-hidden bg-white rounded-lg border border-gray-200 shadow-sm">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th 
                                    scope="col" 
                                    class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6"
                                >
                                    <button
                                        @click="handleSort('name')"
                                        class="group inline-flex items-center gap-x-2 hover:text-gray-900"
                                    >
                                        用户
                                        <span class="flex flex-col -space-y-1">
                                            <ChevronUpIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('name') === 'asc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                            <ChevronDownIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('name') === 'desc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                        </span>
                                    </button>
                                </th>
                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                    邮箱
                                </th>
                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                    状态
                                </th>
                                <th 
                                    scope="col" 
                                    class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
                                >
                                    <button
                                        @click="handleSort('posts_count')"
                                        class="group inline-flex items-center gap-x-2 hover:text-gray-900"
                                    >
                                        文章数
                                        <span class="flex flex-col -space-y-1">
                                            <ChevronUpIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('posts_count') === 'asc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                            <ChevronDownIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('posts_count') === 'desc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                        </span>
                                    </button>
                                </th>
                                <th 
                                    scope="col" 
                                    class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
                                >
                                    <button
                                        @click="handleSort('comments_count')"
                                        class="group inline-flex items-center gap-x-2 hover:text-gray-900"
                                    >
                                        评论数
                                        <span class="flex flex-col -space-y-1">
                                            <ChevronUpIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('comments_count') === 'asc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                            <ChevronDownIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('comments_count') === 'desc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                        </span>
                                    </button>
                                </th>
                                <th 
                                    scope="col" 
                                    class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
                                >
                                    <button
                                        @click="handleSort('created_at')"
                                        class="group inline-flex items-center gap-x-2 hover:text-gray-900"
                                    >
                                        注册时间
                                        <span class="flex flex-col -space-y-1">
                                            <ChevronUpIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('created_at') === 'asc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                            <ChevronDownIcon 
                                                :class="[
                                                    'h-4 w-4 text-gray-400',
                                                    getSortDirection('created_at') === 'desc' ? 'text-orange-600' : ''
                                                ]"
                                            />
                                        </span>
                                    </button>
                                </th>
                                <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                    <span class="sr-only">操作</span>
                                </th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 bg-white">
                            <tr 
                                v-for="user in users.data" 
                                :key="user.id" 
                                class="hover:bg-gray-50 transition-colors"
                            >
                                <td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm sm:pl-6">
                                    <div class="flex items-center gap-x-3">
                                        <div class="h-10 w-10 flex-shrink-0">
                                            <div class="h-10 w-10 rounded-full bg-orange-100 flex items-center justify-center">
                                                <UserIcon class="h-6 w-6 text-orange-600" />
                                            </div>
                                        </div>
                                        <div class="min-w-0 flex-1">
                                            <Link
                                                :href="route('admin.users.show', user.id)"
                                                class="block font-medium text-gray-900 hover:text-orange-600 truncate"
                                            >
                                                {{ user.name }}
                                            </Link>
                                            <div class="mt-0.5 text-xs text-gray-500">
                                                ID: {{ user.id }}
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    {{ user.email }}
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm">
                                    <span
                                        :class="[
                                            'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
                                            user.email_verified_at 
                                                ? 'bg-green-100 text-green-800'
                                                : 'bg-yellow-100 text-yellow-800'
                                        ]"
                                    >
                                        {{ user.email_verified_at ? '已验证' : '未验证' }}
                                    </span>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    <div class="flex items-center gap-x-1">
                                        <DocumentTextIcon class="h-4 w-4 text-gray-400" />
                                        {{ user.posts_count || 0 }}
                                    </div>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    <div class="flex items-center gap-x-1">
                                        <ChatBubbleLeftIcon class="h-4 w-4 text-gray-400" />
                                        {{ user.comments_count || 0 }}
                                    </div>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    {{ formatDate(user.created_at) }}
                                </td>
                                <td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                                    <Menu as="div" class="relative inline-block text-left">
                                        <MenuButton class="inline-flex items-center rounded-full p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 focus:outline-none">
                                            <span class="sr-only">打开选项</span>
                                            <EllipsisHorizontalIcon class="h-5 w-5" />
                                        </MenuButton>
                                        <transition
                                            enter-active-class="transition ease-out duration-100"
                                            enter-from-class="transform opacity-0 scale-95"
                                            enter-to-class="transform opacity-100 scale-100"
                                            leave-active-class="transition ease-in duration-75"
                                            leave-from-class="transform opacity-100 scale-100"
                                            leave-to-class="transform opacity-0 scale-95"
                                        >
                                            <MenuItems class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                                                <div class="py-1">
                                                    <MenuItem v-slot="{ active }">
                                                        <Link
                                                            :href="route('admin.users.show', user.id)"
                                                            :class="[
                                                                active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
                                                                'group flex items-center gap-x-2 px-4 py-2 text-sm'
                                                            ]"
                                                        >
                                                            <EyeIcon class="h-4 w-4" />
                                                            查看
                                                        </Link>
                                                    </MenuItem>
                                                    <MenuItem v-slot="{ active }">
                                                        <Link
                                                            :href="route('admin.users.edit', user.id)"
                                                            :class="[
                                                                active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
                                                                'group flex items-center gap-x-2 px-4 py-2 text-sm'
                                                            ]"
                                                        >
                                                            <PencilIcon class="h-4 w-4" />
                                                            编辑
                                                        </Link>
                                                    </MenuItem>
                                                    <MenuItem v-slot="{ active }">
                                                        <button
                                                            @click="confirmDelete(user)"
                                                            :class="[
                                                                active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
                                                                'group flex w-full items-center gap-x-2 px-4 py-2 text-left text-sm'
                                                            ]"
                                                        >
                                                            <TrashIcon class="h-4 w-4" />
                                                            删除
                                                        </button>
                                                    </MenuItem>
                                                </div>
                                            </MenuItems>
                                        </transition>
                                    </Menu>
                                </td>
                            </tr>
                            <tr v-if="users.data.length === 0">
                                <td colspan="7" class="px-6 py-12 text-center text-sm text-gray-500">
                                    <UserIcon class="mx-auto h-12 w-12 text-gray-400" />
                                    <h3 class="mt-2 font-medium text-gray-900">没有用户</h3>
                                    <p class="mt-1 text-gray-500">开始创建您的第一个用户吧。</p>
                                    <div class="mt-6">
                                        <Link
                                            :href="route('admin.users.create')"
                                            class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500"
                                        >
                                            <PlusIcon class="h-5 w-5" />
                                            新建用户
                                        </Link>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 分页 -->
            <div v-if="users.meta && users.meta.last_page > 1">
                <Pagination :links="users.meta.links || []" />
            </div>
        </div>

        <!-- 删除确认对话框 -->
        <ConfirmDialog
            :show="showDeleteConfirm"
            title="删除用户"
            content="确定要删除此用户吗？此操作不可恢复。"
            confirm-text="删除"
            cancel-text="取消"
            @confirm="deleteUser"
            @close="cancelDelete"
        />
    </AdminLayout>
</template>

